from gtts import gTTS
from playsound import playsound
import re

f = 'D:/project/pythonproject/game_and_utils/py-file/txt_to_audio/'


def remove_consecutive_newlines(text):
    # 使用正则表达式替换连续的换行为单个换行
    cleaned_text = re.sub(r'\n+', '\n', text)
    return cleaned_text


def read(path):
    with open(path, 'r', encoding='UTF-8') as file:
        return file.read()


def read_name(name='input_txt.txt'):
    return read(f + name)


def text_to_speech(text, language='en', output_file='output.mp3'):
    tts = gTTS(text=text, lang=language, slow=False)
    tts.save(output_file)


def play_audio(audio_file):
    playsound(audio_file)


if __name__ == "__main__":
    # 替换为您要转换为语音的中文文字
    text_to_convert = read_name()
    print(text_to_convert)
    text_to_convert = remove_consecutive_newlines(text_to_convert)
    print(text_to_convert)

    # 转换为语音并保存到文件
    text_to_speech(text_to_convert, language='zh-cn', output_file='output.mp3')

    # 播放转换后的语音
    play_audio('output.mp3')
